<template>
  <div class="profile-form-container">
    <el-card class="profile-form-card">
      <div class="profile-header">
        <h2>个人资料设置</h2>
        <p>请完善您的个人信息，帮助我们为您提供更好的健康服务</p>
      </div>
      
      <el-form 
        :model="profileForm" 
        :rules="rules" 
        ref="profileForm" 
        label-width="100px"
        class="profile-form">
        
        <el-form-item label="姓名" prop="fullName">
          <el-input v-model="profileForm.fullName" placeholder="请输入您的姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="profileForm.phoneNumber" placeholder="请输入您的手机号码"></el-input>
        </el-form-item>
        
        <el-form-item label="角色类型" prop="roleTag">
          <el-select v-model="profileForm.roleTag" placeholder="请选择您的角色类型">
            <el-option label="健康追求者" value="健康追求者"></el-option>
            <el-option label="健身爱好者" value="健身爱好者"></el-option>
            <el-option label="慢性病患者" value="慢性病患者"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="身高(cm)" prop="height">
          <el-input-number v-model="profileForm.height" :precision="1" :step="0.1" :min="50" :max="250"></el-input-number>
        </el-form-item>
        
        <el-form-item label="体重(kg)" prop="weight">
          <el-input-number v-model="profileForm.weight" :precision="1" :step="0.1" :min="20" :max="300"></el-input-number>
        </el-form-item>
        
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="profileForm.age" :min="1" :max="120"></el-input-number>
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="profileForm.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
            <el-radio label="other">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm('profileForm')" :loading="loading">保存信息</el-button>
          <el-button @click="resetForm('profileForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'UserProfileForm',
  data() {
    // 手机号码验证规则
    const validatePhone = (rule, value, callback) => {
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (value && !phoneRegex.test(value)) {
        callback(new Error('请输入有效的11位手机号码'));
      } else {
        callback();
      }
    };
    
    return {
      loading: false,
      // 表单数据
      profileForm: {
        userId: null,
        fullName: '',
        phoneNumber: '',
        roleTag: '',
        height: 170.0,
        weight: 60.0,
        age: 25,
        gender: 'male'
      },
      // 表单验证规则
      rules: {
        fullName: [
          { required: true, message: '请输入您的姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        roleTag: [
          { required: true, message: '请选择您的角色类型', trigger: 'change' }
        ],
        height: [
          { required: true, message: '请输入您的身高', trigger: 'blur' }
        ],
        weight: [
          { required: true, message: '请输入您的体重', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入您的年龄', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择您的性别', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    // 从本地存储获取用户ID
    const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
    if (userInfo.id) {
      this.profileForm.userId = userInfo.id;
      this.fetchUserProfile(userInfo.id);
    } else {
      // 如果没有用户ID，重定向到登录页面
      this.$message.warning('请先登录');
      this.$router.push('/');
    }
  },
  methods: {
    // 获取用户资料
    fetchUserProfile() {
      this.axios.get(`/api/userProfile/get`)
        .then(response => {
          if (response.data) {
            // 更新表单数据
            this.profileForm = response.data;
          }
        })
        .catch(error => {
          console.error('获取用户资料失败:', error);
          // 这里不显示错误信息，因为新用户可能还没有资料
        });
    },
    
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          
          // 判断是新增还是更新
          const isUpdate = this.profileForm.id ? true : false;
          
          // API请求
          const apiUrl = isUpdate ? '/api/userProfile/update' : '/api/userProfile/save';
          const method = isUpdate ? 'put' : 'post';
          
          this.axios({
            url: apiUrl,
            method: method,
            data: this.profileForm
          })
            .then(response => {
              this.loading = false;
              this.$message.success('个人资料保存成功');
              
              // 成功后添加一个标记，表示已经有资料了
              sessionStorage.setItem('hasProfile', 'true');
              
              // 使用window.location而不是vue-router进行跳转，绕过导航守卫
              window.location.href = '/home';
            })
            .catch(error => {
              this.loading = false;
              console.error('保存用户资料失败:', error);
              this.$message.error('保存失败，请稍后再试');
            });
        } else {
          return false;
        }
      });
    },
    
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>
.profile-form-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 40px 20px;
  background: linear-gradient(120deg, #e3f2fd, #bbdefb, #fce4ec, #f8bbd0);
}

.profile-form-card {
  width: 100%;
  max-width: 700px;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(33, 150, 243, 0.1);
  background: linear-gradient(to bottom, #ffffff, #f8f8ff);
  border: 1px solid rgba(33, 150, 243, 0.2);
  overflow: hidden;
}

.profile-form-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 6px;
  background: linear-gradient(90deg, #2196f3, #ec407a);
}

.profile-header {
  text-align: center;
  padding: 30px 20px;
  margin-bottom: 20px;
}

.profile-header h2 {
  margin: 0 0 15px;
  font-size: 28px;
  background: linear-gradient(120deg, #1976d2, #d81b60);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-weight: 600;
}

.profile-header p {
  color: #666;
  font-size: 16px;
  max-width: 500px;
  margin: 0 auto;
}

.profile-form {
  padding: 20px 40px 40px;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-form-item.is-required .el-form-item__label::before {
  color: #f56c6c;
}

.el-input >>> .el-input__inner,
.el-select >>> .el-input__inner {
  border-radius: 8px;
  height: 42px;
  line-height: 42px;
}

.el-input-number {
  width: 180px;
}

.el-button {
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
}

.el-button--primary {
  background: linear-gradient(90deg, #409EFF, #E040FB) !important;
  border: none !important;
  transition: all 0.3s ease !important;
  font-weight: 500;
  letter-spacing: 1px;
}

.el-button--primary:hover {
  opacity: 0.9;
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(33, 150, 243, 0.2);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .profile-form {
    padding: 20px;
  }
  
  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>
